<template>
  <div class="trade-info-container">
    <!-- 背景装饰层 -->
    <div class="background-decoration"></div>

    <div class="form-card">
      <h2>个人交易信息</h2>
      <el-form label-width="120px">
        <!-- 表单字段保持不变 -->
        <el-form-item label="真实姓名">
          <el-input v-model="user.zm" placeholder="请填写真实有效的姓名" style="width: 300px"></el-input>
        </el-form-item>
        <el-form-item label="登录邮箱地址">
          <el-input v-model="user.email" placeholder="请填写您的邮箱地址" style="width: 300px"></el-input>
        </el-form-item>
        <el-form-item label="个人所在地">
          <div class="location-input-group">
            <el-cascader
                v-model="selectedLocation"
                :options="regionOptions"
                placeholder="选择个人所在地"
                style="width: 220px"
                :props="{ expandTrigger: 'hover' }"
                @change="handleLocationChange"
            ></el-cascader>
            <el-button @click="getLocation" type="default" size="small" style="margin-left: 8px;">
              <i class="el-icon-location"></i> 从定位获取
            </el-button>
          </div>
        </el-form-item>
        <el-form-item label="详细地址">
          <el-input v-model="user.address" placeholder="请填写详细地址信息" style="width: 300px"></el-input>
        </el-form-item>
        <el-form-item label="电话号码">
          <el-input v-model="user.phone" placeholder="请填写手机号码" style="width: 300px"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="saveUserInfo">确定</el-button>
          <el-button>取消</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 定位确认对话框 -->
    <el-dialog
        v-model="locationDialogVisible"
        title="确认定位信息"
        width="400px"
        :before-close="handleDialogClose"
    >
      <div class="location-dialog-content">
        <p>检测到您的位置信息如下：</p>
        <div class="location-info">{{ tempLocationText }}</div>

        <div class="modify-section" v-if="showModifyCascader">
          <p style="margin: 15px 0 5px;">如需修改，请选择：</p>
          <el-cascader
              v-model="tempSelectedLocation"
              :options="regionOptions"
              placeholder="重新选择所在地"
              style="width: 100%"
              :props="{ expandTrigger: 'hover' }"
              @change="handleTempLocationChange"
          ></el-cascader>
        </div>

        <el-checkbox v-model="showModifyCascader" style="margin-top: 10px;">
          不使用当前定位，手动修改
        </el-checkbox>
      </div>
      <template #footer>
        <el-button @click="locationDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmLocation">确认使用</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { AuthService } from '../../service/auth';
import axios from "axios";
import { ElMessage, ElLoading } from "element-plus";
import { regionData } from 'element-china-area-data';
import { getCurrentLocation } from '../../service/geolocation';

const authService = new AuthService();
const userId = authService.getUserId();

// 表单数据
const user = ref({
  id: '',
  username: '',
  address: '',
  phone: '',
  location: '', // 存储完整地址字符串，如"广西壮族自治区/南宁市/兴宁区"
  zm: '',
  email: ''
});

// 级联选择器相关
const selectedLocation = ref([]);
const regionOptions = ref(regionData);

// 定位对话框相关
const locationDialogVisible = ref(false);
const tempLocationText = ref(''); // 临时存储定位地址文本
const tempSelectedLocation = ref([]); // 临时存储级联选择值
const showModifyCascader = ref(false); // 是否显示修改用的级联选择器

// 获取用户信息
const getUserInfo = async () => {
  try {
    const { data } = await axios.get(`/api/user/getUserById/${userId}`);
    user.value = data;
    if (data.location) {
      selectedLocation.value = convertLocationStringToCodes(data.location);
    }
  } catch (error) {
    ElMessage.error('获取用户信息失败');
  }
};

// 地址字符串转编码数组
const convertLocationStringToCodes = (locationStr) => {
  if (!locationStr) return [];
  const locations = locationStr.split('/');
  const result = [];
  let currentOptions = regionOptions.value;
  for (let i = 0; i < locations.length; i++) {
    const locationName = locations[i];
    const option = currentOptions.find(item => item.label === locationName);
    if (option) {
      result.push(option.value);
      if (option.children) currentOptions = option.children;
      else break;
    } else break;
  }
  return result;
};

// 编码数组转地址字符串
const convertCodesToLocationString = (codes) => {
  if (!codes || codes.length === 0) return '';
  const labels = [];
  let currentOptions = regionOptions.value;
  for (const code of codes) {
    const option = currentOptions.find(item => item.value === code);
    if (option) {
      labels.push(option.label);
      if (option.children) currentOptions = option.children;
      else break;
    } else break;
  }
  return labels.join('/');
};

// 处理级联选择变化
const handleLocationChange = (value) => {
  user.value.location = convertCodesToLocationString(value);
};

// 处理临时级联选择变化（对话框内）
const handleTempLocationChange = (value) => {
  tempLocationText.value = convertCodesToLocationString(value);
};

// 保存用户信息
const saveUserInfo = async () => {
  try {
    await axios.put(`/api/user`, user.value);
    ElMessage.success('保存成功');
  } catch (error) {
    ElMessage.error('保存失败');
  }
};

// 获取定位并显示对话框
const getLocation = async () => {
  try {
    const loading = ElLoading.service({
      lock: true,
      text: '正在获取位置信息...',
      background: 'rgba(0, 0, 0, 0.7)'
    });

    // 获取经纬度
    const position = await getCurrentLocation({
      enableHighAccuracy: true,
      timeout: 10000
    });

    // 转换为地址信息
    const { data } = await axios.get(`/api/user/gaode/coordinate`, {
      params: {
        lat: position.latitude,
        lng: position.longitude
      }
    });

    // 构建地址字符串
    const { province, city, district } = data.regeocode.addressComponent;
    const locationStr = [province, city, district].filter(Boolean).join('/');

    // 初始化对话框数据
    tempLocationText.value = locationStr;
    tempSelectedLocation.value = convertLocationStringToCodes(locationStr);
    showModifyCascader.value = false;
    locationDialogVisible.value = true;

    loading.close();
  } catch (error) {
    ElMessage.error('获取定位失败，请手动选择');
    console.error('定位错误:', error);
  }
};

// 确认定位信息
const confirmLocation = () => {
  // 使用临时选择的值更新表单
  selectedLocation.value = [...tempSelectedLocation.value];
  user.value.location = tempLocationText.value;
  locationDialogVisible.value = false;
  ElMessage.success('位置信息已更新');
};

// 关闭对话框时重置临时数据
const handleDialogClose = () => {
  tempSelectedLocation.value = [];
  tempLocationText.value = '';
  showModifyCascader.value = false;
  locationDialogVisible.value = false;
};

onMounted(() => {
  getUserInfo();
});
</script>

<style scoped>
.trade-info-container {
  padding: 40px 20px;
  min-height: 100vh;
  position: relative;
  overflow: hidden;
  /* 柔和的背景渐变 */
  background: linear-gradient(135deg, #f9fafb 0%, #f0f4f8 100%);
}

/* 背景装饰元素 - 柔和纹理图 */
.background-decoration {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 0;
  background-image:
      url('/VCG41N1266262404.jpg'),
      radial-gradient(circle at 20% 30%, rgba(120, 180, 255, 0.04) 0%, transparent 30%),
      radial-gradient(circle at 80% 70%, rgba(180, 220, 255, 0.04) 0%, transparent 30%);
  background-blend-mode: overlay;
  background-size: cover;
  background-position: center;
  pointer-events: none;
}

/* 表单卡片样式 */
.form-card {
  position: relative;
  z-index: 1;
  max-width: 600px;
  margin: 0 auto;
  padding: 30px;
  background-color: rgba(255, 255, 255, 0.97);
  border-radius: 12px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.06);
  backdrop-filter: blur(8px);
}

/* 标题样式 */
.form-card h2 {
  color: #2c3e50;
  margin-bottom: 25px;
  padding-bottom: 15px;
  border-bottom: 1px solid #f0f2f5;
  font-weight: 600;
  position: relative;
}

.form-card h2::after {
  content: '';
  position: absolute;
  left: 0;
  bottom: -1px;
  width: 60px;
  height: 3px;
  background: linear-gradient(90deg, #6ea8fe, #9cbbff);
  border-radius: 3px;
}

.location-input-group {
  display: flex;
  align-items: center;
}

/* 输入框聚焦效果增强 */
:deep(.el-input__wrapper):focus-within {
  box-shadow: 0 0 0 2px rgba(110, 168, 254, 0.2);
  border-color: #6ea8fe;
}

/* 按钮样式优化 */
:deep(.el-button--primary) {
  background: linear-gradient(90deg, #6ea8fe, #9cbbff);
  border: none;
  transition: all 0.3s ease;
}

:deep(.el-button--primary):hover {
  background: linear-gradient(90deg, #5a96f7, #8bb0f8);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(110, 168, 254, 0.3);
}

/* 对话框样式增强 */
:deep(.el-dialog__body) {
  padding: 20px;
}

.location-dialog-content {
  line-height: 1.6;
}

.location-info {
  padding: 10px;
  margin: 10px 0;
  background-color: #f5f7fa;
  border-radius: 4px;
  border-left: 3px solid #6ea8fe;
}

.modify-section {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px dashed #e5e7eb;
}
</style>